﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Globalization;
using System.Text.RegularExpressions;
using System.Web;


public static class CoString
{

    private static readonly string cnNumber = "零壹贰叁肆伍陆柒捌玖";
    private static readonly string cnUnit = "分角元拾佰仟万拾佰仟亿拾佰仟兆拾佰仟";

    private static readonly string[] enSmallNumber = { "", "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE", "TEN", "ELEVEN", "TWELVE", "THIRTEEN", "FOURTEEN", "FIFTEEN", "SIXTEEN", "SEVENTEEN", "EIGHTEEN", "NINETEEN" };
    private static readonly string[] enLargeNumber = { "TWENTY", "THIRTY", "FORTY", "FIFTY", "SIXTY", "SEVENTY", "EIGHTY", "NINETY" };
    private static readonly string[] enUnit = { "", "THOUSAND", "MILLION", "BILLION", "TRILLION" };

    /// <summary>
    /// 点符号 .
    /// </summary>
    public const string Dot = ".";

    /// <summary>
    /// 下划线 _
    /// </summary>
    public const string UnderScore = "_";

    /// <summary>
    /// 逗号加空格 , 
    /// </summary>
    public const string CommaSpace = ", ";

    /// <summary>
    /// 逗号 ,
    /// </summary>
    public const string Comma = ",";

    /// <summary>
    /// 左括号 (
    /// </summary>
    public const string OpenParen = "(";

    /// <summary>
    /// 右括号 )
    /// </summary>
    public const string ClosedParen = ")";

    /// <summary>
    /// 单引号 '
    /// </summary>
    public const string SingleQuote = "\'";

    /// <summary>
    /// 斜线 \
    /// </summary>
    public const string Slash = @"\";




    /// <summary>
    /// 移除空格并首字母小写的Camel样式
    /// </summary>
    /// <param name="name"></param>
    /// <returns></returns>
    public static string ToCamel(this string name)
    {
        string clone = name.TrimStart('_');
        clone = RemoveSpaces(ToProperCase(clone));
        return string.Format("{0}{1}", Char.ToLower(clone[0]), clone.Substring(1, clone.Length - 1));
    }

    /// <summary>
    /// 移除空格并首字母大写的Pascal样式
    /// </summary>
    /// <param name="name"></param>
    /// <returns></returns>
    public static string ToCapit(this string name)
    {
        string clone = name.TrimStart('_');
        return RemoveSpaces(ToProperCase(clone));
    }


    /// <summary>
    /// 移除最后的字符
    /// </summary>
    /// <param name="s"></param>
    /// <returns></returns>
    public static string RemoveFinalChar(this string s)
    {
        if (s.Length > 1)
        {
            s = s.Substring(0, s.Length - 1);
        }
        return s;
    }
    /// <summary>
    /// 移除最后的字符
    /// </summary>
    /// <param name="s"></param>
    /// <returns></returns>
    public static string RemoveFinalChar(this string s, int count)
    {
        if (s.Length > 1)
        {
            s = s.Substring(0, s.Length - count);
        }
        return s;
    }
    /// <summary>
    /// 移除最后的逗号
    /// </summary>
    /// <param name="s"></param>
    /// <returns></returns>
    public static string RemoveFinalComma(this string s)
    {
        if (s.Trim().Length > 0)
        {
            int c = s.LastIndexOf(",");
            if (c > 0)
            {
                s = s.Substring(0, s.Length - (s.Length - c));
            }
        }
        return s;
    }

    /// <summary>
    /// 移除字符中的空格
    /// </summary>
    /// <param name="s"></param>
    /// <returns></returns>
    public static string RemoveSpaces(this string s)
    {
        s = s.Trim();
        s = s.Replace(" ", "");
        return s;
    }

    /// <summary>
    /// 字符串首字母大写
    /// </summary>
    /// <param name="s"></param>
    /// <returns></returns>
    public static string ToProperCase(this string s)
    {
        string str = s.Substring(0, 1).ToUpper() + s.Substring(1);
        return str;
    }
    /// <summary>
    /// 字符串截取
    /// </summary>
    /// <param name="s"></param>
    /// <param name="length">要截取的长度</param>
    /// <param name="isHaveSp">截取后的字符串是否包含省略号(...)</param>
    /// <returns></returns>
    public static string SubString(this string s, int length, string def)
    {
        if (s.Length < length)
            return s;

       return s.Substring(0, length) + def;
   

    }

    /// <summary>
    /// 判断字符是否NULL或者为空
    /// </summary>
    public static bool IsNullOrEmpty(this string value)
    {
        if (value == null || value == string.Empty)
        {
            return true;
        }

        return false;
    }





    /// <summary>
    /// 以下是货币金额中文大写转换方法
    /// </summary>
    /// <param name="s"></param>
    /// <returns></returns>
    public static string GetCnstring(this string s)
    {
        string[] tmpstring = s.Split('.');
        string intstring = s;   // 默认为整数
        string decstring = "";            // 保存小数部分字串
        string rmbCapital = "";            // 保存中文大写字串
        int k;
        int j;
        int n;

        if (tmpstring.Length > 1)
        {
            intstring = tmpstring[0];             // 取整数部分
            decstring = tmpstring[1];             // 取小数部分
        }
        decstring += "00";
        decstring = decstring.Substring(0, 2);   // 保留两位小数位
        intstring += decstring;

        try
        {
            k = intstring.Length - 1;
            if (k > 0 && k < 18)
            {
                for (int i = 0; i <= k; i++)
                {
                    j = (int)intstring[i] - 48;
                    // rmbCapital = rmbCapital + cnNumber[j] + cnUnit[k-i];     // 供调试用的直接转换
                    n = i + 1 >= k ? (int)intstring[k] - 48 : (int)intstring[i + 1] - 48; // 等效于 if( ){ }else{ }
                    if (j == 0)
                    {
                        if (k - i == 2 || k - i == 6 || k - i == 10 || k - i == 14)
                        {
                            rmbCapital += cnUnit[k - i];
                        }
                        else
                        {
                            if (n != 0)
                            {
                                rmbCapital += cnNumber[j];
                            }
                        }
                    }
                    else
                    {
                        rmbCapital = rmbCapital + cnNumber[j] + cnUnit[k - i];
                    }
                }

                rmbCapital = rmbCapital.Replace("兆亿万", "兆");
                rmbCapital = rmbCapital.Replace("兆亿", "兆");
                rmbCapital = rmbCapital.Replace("亿万", "亿");
                rmbCapital = rmbCapital.TrimStart('元');
                rmbCapital = rmbCapital.TrimStart('零');

                return rmbCapital;
            }
            else
            {
                return "";   // 超出转换范围时，返回零长字串
            }
        }
        catch
        {
            return "";   // 含有非数值字符时，返回零长字串
        }
    }

    /// <summary>
    /// 以下是货币金额英文大写转换方法
    /// </summary>
    /// <param name="s"></param>
    /// <returns></returns>
    public static string GetEnstring(this string s)
    {
        string[] tmpstring = s.Split('.');
        string intstring = s;   // 默认为整数
        string decstring = "";            // 保存小数部分字串
        string engCapital = "";            // 保存英文大写字串
        string strBuff1;
        string strBuff2;
        string strBuff3;
        int curPoint;
        int i1;
        int i2;
        int i3;
        int k;
        int n;

        if (tmpstring.Length > 1)
        {
            intstring = tmpstring[0];             // 取整数部分
            decstring = tmpstring[1];             // 取小数部分
        }
        decstring += "00";
        decstring = decstring.Substring(0, 2);   // 保留两位小数位

        try
        {
            // 以下处理整数部分
            curPoint = intstring.Length - 1;
            if (curPoint >= 0 && curPoint < 15)
            {
                k = 0;
                while (curPoint >= 0)
                {
                    strBuff1 = "";
                    strBuff2 = "";
                    strBuff3 = "";
                    if (curPoint >= 2)
                    {
                        n = int.Parse(intstring.Substring(curPoint - 2, 3));
                        if (n != 0)
                        {
                            i1 = n / 100;            // 取佰位数值
                            i2 = (n - i1 * 100) / 10;    // 取拾位数值
                            i3 = n - i1 * 100 - i2 * 10;   // 取个位数值
                            if (i1 != 0)
                            {
                                strBuff1 = enSmallNumber[i1] + " HUNDRED ";
                            }
                            if (i2 != 0)
                            {
                                if (i2 == 1)
                                {
                                    strBuff2 = enSmallNumber[i2 * 10 + i3] + " ";
                                }
                                else
                                {
                                    strBuff2 = enLargeNumber[i2 - 2] + " ";
                                    if (i3 != 0)
                                    {
                                        strBuff3 = enSmallNumber[i3] + " ";
                                    }
                                }
                            }
                            else
                            {
                                if (i3 != 0)
                                {
                                    strBuff3 = enSmallNumber[i3] + " ";
                                }
                            }
                            engCapital = strBuff1 + strBuff2 + strBuff3 + enUnit[k] + " " + engCapital;
                        }
                    }
                    else
                    {
                        n = int.Parse(intstring.Substring(0, curPoint + 1));
                        if (n != 0)
                        {
                            i2 = n / 10;      // 取拾位数值
                            i3 = n - i2 * 10;   // 取个位数值
                            if (i2 != 0)
                            {
                                if (i2 == 1)
                                {
                                    strBuff2 = enSmallNumber[i2 * 10 + i3] + " ";
                                }
                                else
                                {
                                    strBuff2 = enLargeNumber[i2 - 2] + " ";
                                    if (i3 != 0)
                                    {
                                        strBuff3 = enSmallNumber[i3] + " ";
                                    }
                                }
                            }
                            else
                            {
                                if (i3 != 0)
                                {
                                    strBuff3 = enSmallNumber[i3] + " ";
                                }
                            }
                            engCapital = strBuff2 + strBuff3 + enUnit[k] + " " + engCapital;
                        }
                    }

                    ++k;
                    curPoint -= 3;
                }
                engCapital = engCapital.TrimEnd();
            }


            // 以下处理小数部分
            strBuff2 = "";
            strBuff3 = "";
            n = int.Parse(decstring);
            if (n != 0)
            {
                i2 = n / 10;      // 取拾位数值
                i3 = n - i2 * 10;   // 取个位数值
                if (i2 != 0)
                {
                    if (i2 == 1)
                    {
                        strBuff2 = enSmallNumber[i2 * 10 + i3] + " ";
                    }
                    else
                    {
                        strBuff2 = enLargeNumber[i2 - 2] + " ";
                        if (i3 != 0)
                        {
                            strBuff3 = enSmallNumber[i3] + " ";
                        }
                    }
                }
                else
                {
                    if (i3 != 0)
                    {
                        strBuff3 = enSmallNumber[i3] + " ";
                    }
                }

                // 将小数字串追加到整数字串后
                if (engCapital.Length > 0)
                {
                    engCapital = engCapital + " AND CENTS " + strBuff2 + strBuff3;   // 有整数部分时
                }
                else
                {
                    engCapital = "CENTS " + strBuff2 + strBuff3;   // 只有小数部分时
                }
            }

            engCapital = engCapital.TrimEnd();
            return engCapital;
        }
        catch
        {
            return "";   // 含非数字字符时，返回零长字串
        }
    }


    /// <summary>
    /// Texts to HTML.
    /// </summary>
    /// <param name="txtStr">The TXT STR.</param>
    /// <returns>The formated str.</returns>
    public static string TextToHtml(this string content)
    {
        StringBuilder sb = new StringBuilder(content);
        sb.Replace("&", "&amp;");
        sb.Replace("<", "&lt;");
        sb.Replace(">", "&gt;");
        sb.Replace("\"", "&quot;");
        //     sb.Replace("\'", "&#39;");
        sb.Replace(" ", "&nbsp;");
        sb.Replace("\t", "&nbsp;&nbsp;");
        sb.Replace("\r", "");
        sb.Replace("\n", "<br />");
        return sb.ToString();
        //  return ShitEncode(sb.ToString());

        //return content.Replace(" ", "&nbsp;").Replace("\t", "&nbsp;&nbsp;&nbsp;&nbsp;").
        //    Replace("<", "&lt;").Replace(">", "&gt;").Replace("\r", "").Replace("\n", "<br />");
    }

    /// <summary>
    /// html to text
    /// </summary>
    /// <param name="content"></param>
    /// <returns></returns>
    public static string HtmlToText(this string content)
    {
        StringBuilder sb = new StringBuilder(content);
        sb.Replace("<br />", "\n");
        sb.Replace("<br/>", "\n");
        //  sb.Replace("\r", "");
        sb.Replace("&nbsp;&nbsp;", "\t");
        sb.Replace("&nbsp;", " ");
        sb.Replace("&#39;", "\'");
        sb.Replace("&quot;", "\"");
        sb.Replace("&gt;", ">");
        sb.Replace("&lt;", "<");
        sb.Replace("&amp;", "&");


        return sb.ToString();
    }
    /// <summary>
    /// 删除字符串中对win下新建文件夹造成威胁的字符
    /// </summary>
    /// <param name="content"></param>
    /// <returns></returns>
    public static string DelectStrByWinFolder(this string content)
    {
        StringBuilder sb = new StringBuilder(content);
        sb.Replace("|", "_");
        sb.Replace(":", "_");
        sb.Replace(";", "_");
        sb.Replace("'", "_");
        sb.Replace("\"", "_");
        sb.Replace("\\", "_");
        sb.Replace("//", "_");
        sb.Replace("?", "_");
        sb.Replace("*", "_");
        return sb.ToString();
    }

    /// <summary>
    /// HtmlEncode
    /// </summary>
    /// <param name="content"></param>
    /// <returns></returns>
    public static string HtmlEncode(this string content)
    {
        if (string.IsNullOrEmpty(content))
            return "";

        return HttpContext.Current.Server.HtmlEncode(content);
    }

    /// <summary>
    ///  HtmlDecode
    /// </summary>
    /// <param name="content"></param>
    /// <returns></returns>
    public static string HtmlDecode(this string content)
    {
        if (string.IsNullOrEmpty(content))
            return "";
        string temp = HttpContext.Current.Server.HtmlDecode(content);
        temp = HttpContext.Current.Server.HtmlDecode(temp);
        //temp = HttpContext.Current.Server.HtmlDecode(temp);
        return temp;
    }

    /// <summary>
    /// 返回 URL 字符串的编码结果
    /// </summary>
    /// <param name="str">字符串</param>
    /// <returns>编码结果</returns>
    public static string UrlEncode(this string str)
    {
        if (string.IsNullOrEmpty(str))
            return "";

        return HttpUtility.UrlEncode(str);
    }

    /// <summary>
    /// 返回 URL 字符串的编码结果
    /// </summary>
    /// <param name="str">字符串</param>
    /// <returns>解码结果</returns>
    public static string UrlDecode(this string str)
    {
        if (string.IsNullOrEmpty(str))
            return "";
        return HttpUtility.UrlDecode(str);
    }




    /// <summary>
    /// 返回字符串真实长度, 1个汉字长度为2
    /// </summary>
    /// <returns></returns>
    public static int GetLength(this string str)
    {
        if (string.IsNullOrEmpty(str))
        {
            return 0;
        }
        return Encoding.Default.GetBytes(str).Length;
    }

    /// <summary>
    /// 编码成 sql 文本可以接受的格式
    /// </summary>
    public static string SqlEncode(this string s)
    {
        if (null == s || 0 == s.Length)
        {
            return string.Empty;
        }

        return s.Trim().Replace("'", "''");
    }




    /// <summary>
    /// 从字符串的指定位置截取指定长度的子字符串(过时)
    /// </summary>
    /// <param name="str">原字符串</param>
    /// <param name="startIndex">子字符串的起始位置</param>
    /// <param name="length">子字符串的长度</param>
    /// <returns>子字符串</returns>
    public static string CutString(this string str, int startIndex, int length)
    {
        return CutString(str, startIndex, length, string.Empty);
    }

    /// <summary>
    /// 从字符串的指定位置开始截取到字符串结尾的了符串
    /// </summary>
    /// <param name="str">原字符串</param>
    /// <param name="startIndex">子字符串的起始位置</param>
    /// <returns>子字符串</returns>
    public static string CutString(this string str, int length)
    {
        return CutString(str, 0, length, string.Empty);
    }

    /// <summary>
    /// 截取字符
    /// </summary>
    /// <param name="str"></param>
    /// <param name="length"></param>
    /// <param name="def"></param>
    /// <returns></returns>
    public static string CutString(this string str, int length, string def)
    {
        return CutString(str, 0, length, def);
    }

    public static string CutString(this string str, int startIndex, int length, string def)
    {
        if (startIndex >= 0)
        {
            if (length < 0)
            {
                length = length * -1;
                if (startIndex - length < 0)
                {
                    length = startIndex;
                    startIndex = 0;
                }
                else
                {
                    startIndex = startIndex - length;
                }
            }


            if (startIndex > str.Length)
            {
                return "";
            }


        }
        else
        {
            if (length < 0)
            {
                return "";
            }
            else
            {
                if (length + startIndex > 0)
                {
                    length = length + startIndex;
                    startIndex = 0;
                }
                else
                {
                    return "";
                }
            }
        }

        if (str.Length - startIndex <= length)
        {
            length = str.Length - startIndex;
            def = string.Empty;
        }

        try
        {
            return str.Substring(startIndex, length) + def;
        }
        catch
        {
            return str + def;
        }
    }


    /// <summary>
    /// 移除Html标记
    /// </summary>
    /// <param name="Content"></param>
    /// <returns></returns>
    public static string RemoveHtml(this string Content)
    {
        string regexstr = @"<[^>]*>";
        return Regex.Replace(Content, regexstr, string.Empty, RegexOptions.IgnoreCase).Trim();
    }



    /// <summary>
    /// string型转换为int型,转换失敗返回缺省值
    /// </summary>
    /// <param name="str">要转换的字符串</param>
    /// <param name="def">缺省值</param>
    /// <returns>转换后的int类型结果</returns>
    public static int ToInt(this string str, int def)
    {

        if (str.IsInt())
        {
            return int.Parse(str);
        }
        else
        {
            return def;
        }
    }

    /// <summary>
    /// string型转换为bool型,转换失敗返回缺省值
    /// </summary>
    /// <param name="str">要转换的字符串</param>
    /// <param name="def">缺省值</param>
    /// <returns>转换后的int类型结果</returns>
    public static bool ToBool(this string str, bool def)
    {

        try
        {
            return Convert.ToBoolean(str);
        }
        catch (Exception)
        {

            return def;
        }

    }


    /// <summary>
    /// 返回URL中结尾的文件名
    /// </summary>		
    public static string GetFileName(this string url)
    {
        //	HttpContext.Current.Response.Write( url.IndexOf("?"));

        if (url == null)
        {
            return "";
        }
        //是否有参数
        if (url.IndexOf("?") != -1)
        {
            //去掉参数
            string noquery = url.Substring(0, url.IndexOf("?"));

            //根据/分组
            string[] filenames = noquery.Split(new char[] { '/' });

            //文件名
            string filename = filenames[filenames.Length - 1];

            return filename;
        }
        else
        {
            return System.IO.Path.GetFileName(url);
        }


    }
    /// <summary>
    /// 返回U文件的后缀
    /// </summary>		
    public static string GetFileExt(this string fileName)
    {
      
        if (fileName == null)
        {
            return "";
        }
       
        if (fileName.IndexOf(".") != -1)
            return fileName.Substring(fileName.LastIndexOf("."));
        else
            return "";


    }


    /// <summary>
    /// 将时间换成中文
    /// </summary>
    /// <param name="datetime">时间</param>
    /// <returns></returns>
    public static string DateToChineseString(this DateTime datetime)
    {
        TimeSpan ts = DateTime.Now - datetime;
        //    System.Web.HttpContext.Current.Response.Write(ts.TotalDays);
        if ((int)ts.TotalDays >= 365)
        {
            return (int)ts.TotalDays / 365 + "年前";
        }
        if ((int)ts.TotalDays >= 30 && ts.TotalDays <= 365)
        {
            return (int)ts.TotalDays / 30 + "月前";
        }
        if ((int)ts.TotalDays == 1)
        {
            return "昨天";
        }
        if ((int)ts.TotalDays == 2)
        {
            return "前天";
        }
        if ((int)ts.TotalDays >= 3 && ts.TotalDays <= 30)
        {
            return (int)ts.TotalDays + "天前";
        }
        if ((int)ts.TotalDays == 0)
        {
            if ((int)ts.TotalHours != 0)
            {
                return (int)ts.TotalHours + "小时前";
            }
            else
            {
                if ((int)ts.TotalMinutes == 0)
                {
                    return "1分钟前";
                }
                else
                {
                    return (int)ts.TotalMinutes + "分钟前";
                }
            }
        }
        return datetime.ToString("yyyy年MM月dd日 HH:mm");
    }



    public static int ObjectToInt(this object o)
    {
        return ObjectToInt(o, 0);
    }

    /// <summary>
    /// 将对象转换为Int32类型
    /// </summary>
    /// <param name="expression"></param>
    /// <param name="defValue"></param>
    /// <returns></returns>
    public static int ObjectToInt(this object o, int defValue)
    {
        if (o != null)
            return ToInt(o.ToString(), defValue);

        return defValue;
    }

}


